﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Threading;

namespace Innovox.NetTools
{
    class HttpRequestStreamReader
    {
        const int BUFFER_SIZE = 3072;
        const int ReadTimeout = 20000;

        byte[] bufferRead;
        Stream streamResponse;
        HttpRequestContext context;

        public HttpRequestStreamReader(HttpRequestContext context)
        {
            this.context = context;
            bufferRead = new byte[BUFFER_SIZE];
            streamResponse = null;
        }

        public void BeginRead()
        {
            try
            {
                // Read the response into a Stream object.
                streamResponse = context.GetResponseStream();
                // Begin the Reading of the contents of the HTML page
                BeginReadingStream(streamResponse);
                return;
            }
            catch (Exception e)//(WebException e)
            {
                context.AbortRequest();
                context.SetErrorMessage(e.Message);
            }
            context.SetAllDone();
        }

        private static void TimeoutCallback(object state, bool timedOut)
        {
            if (timedOut)
            {
                HttpRequestContext context = state as HttpRequestContext;
                if (context != null)
                    context.AbortRequest();
               // context.SetAllDone();
            }
        }

        private static void ReadCallBack(IAsyncResult asyncResult)
        {
            HttpRequestStreamReader requestReader = (HttpRequestStreamReader) asyncResult.AsyncState as HttpRequestStreamReader;
            HttpRequestContext context = requestReader.context;

            try
            {
                Stream responseStream = requestReader.streamResponse;
                int bytesRead = responseStream.EndRead(asyncResult);
                if (bytesRead > 0)
                {
                    context.AppendBytesToRequestData(requestReader.bufferRead, bytesRead);
                    requestReader.BeginReadingStream(responseStream);
                    return;
                }
                else
                    responseStream.Close();

            }
            catch (Exception e)
            {
                context.SetErrorMessage(e.Message);
            }
            context.SetAllDone();
        }

        public void BeginReadingStream(Stream streamResponse)
        {
            IAsyncResult asyncResult = streamResponse.BeginRead(this.bufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), this);
            ThreadPool.RegisterWaitForSingleObject(asyncResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), context, ReadTimeout, true);
        }
    }
}
